'use strict';

//文件上传实例之头像上传
angular.module('User')
    .controller('UploadController', ['$scope', '$cookies', '$timeout', '$window', 'Initialization', 'FileUploader',
        function ($scope, $cookies, $timeout, $window, Initialization, FileUploader) {
            $scope.data = {
                url: 'http://localhost:3000/api/fileUpload',
                Authorization: 'Bearer ' + $cookies.get('U9USS'),
                uploadType: 'avatar',
                filePath: './public/users/img/',
                src: ''
            };

            //$scope.data = {
            //    url: 'http://localhost:3000/api/fileUpload',
            //    Authorization: 'Bearer ' + $cookies.get('U9USS'),
            //    uploadType: 'avatar',
            //    filePath: './public/img/'
            //};

            function saveImage(file) {
                var form = new FormData();
                form.append('file', file);
                form.append('uploadType', $scope.data.uploadType);
                form.append('filePath', $scope.data.filePath);

                var request = new XMLHttpRequest();
                request.open("POST", $scope.data.url);
                request.setRequestHeader("Authorization", $scope.data.Authorization);
                request.send(form);
            }

            //将base64转成Blob
            function convertBase64UrlToBlob(urlData) {
                var bytes = window.atob(urlData.split(',')[1]);
                //去掉url的头，并转换为byte
                //处理异常,将ascii码小于0的转换为大于0
                var ab = new ArrayBuffer(bytes.length);
                var ia = new Uint8Array(ab);
                for (var i = 0; i < bytes.length; i++) {
                    ia[i] = bytes.charCodeAt(i);
                }

                return new Blob([ab], {type: 'image/png'});
            }

            $scope.uploadProfilePicture = function () {
                var form = new FormData();
                form.append('file', file);
                form.append('uploadType', $scope.data.uploadType);
                form.append('filePath', $scope.data.filePath);

                var request = new XMLHttpRequest();
                request.open("POST", $scope.data.url);
                request.setRequestHeader("Authorization", $scope.data.Authorization);
                request.send(form);
            };
        }
    ]);
